package svc

import (
	"encoding/binary"
	"fmt"
	"strings"
	"time"
)

const (
	FlagDelete = iota
	FlagInit
)

type FileInfo struct {
	ID       int `storm:"id,increment"`
	Fid      uint64
	Offset   uint64
	Size     uint64
	Ctime    time.Time
	Mtime    time.Time
	Flag     int
	FileName string
	MD       string
}

func (f *FileInfo) MarshalBinary() []byte {
	data := make([]byte, 48+3+len(f.MD)+len(f.FileName))
	binary.BigEndian.PutUint64(data[0:8], f.Fid)
	binary.BigEndian.PutUint64(data[8:16], f.Offset)
	binary.BigEndian.PutUint64(data[16:24], f.Size)
	binary.BigEndian.PutUint64(data[24:32], uint64(f.Ctime.Unix()))
	binary.BigEndian.PutUint64(data[32:40], uint64(f.Mtime.Unix()))
	binary.BigEndian.PutUint64(data[40:48], uint64(f.Flag))
	copy(data[48:], fmt.Sprintf("%s&,&%s", f.MD, f.FileName))
	return data
}

func (f *FileInfo) UnMarshalBinary(data []byte) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
	}()
	f.Fid = binary.BigEndian.Uint64(data[0:8])
	f.Offset = binary.BigEndian.Uint64(data[8:16])
	f.Size = binary.BigEndian.Uint64(data[16:24])
	f.Ctime = time.Unix(int64(binary.BigEndian.Uint64(data[24:32])), 0)
	f.Mtime = time.Unix(int64(binary.BigEndian.Uint64(data[32:40])), 0)
	f.Flag = int(binary.BigEndian.Uint64(data[40:48]))
	lastStr := strings.Split(string(data[48:]), "&,&")
	if len(lastStr) == 2 {
		f.MD = lastStr[0]
		f.FileName = lastStr[1]
	}
	return err
}
